package org.jeecgframework.web.service.impl;

import org.apache.batik.apps.rasterizer.Main;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DataUtils;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.CbsInspectionAppointmentServiceI;
import org.jeecgframework.web.system.pojo.base.CbsInspectionAppointmentEntity;
import org.jeecgframework.web.system.pojo.base.CbsInspectionAppointmentEsEntity;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentSpareEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SectionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.NumberFormat;
import java.util.*;
import java.io.Serializable;

@Service("cbsInspectionAppointmentService")
@Transactional
public class CbsInspectionAppointmentServiceImpl extends CommonServiceImpl implements CbsInspectionAppointmentServiceI {

    private static final Logger logger = Logger.getLogger(CbsInspectionAppointmentServiceImpl.class);

    @Autowired
    private SystemService systemService;

    public <T> void delete(T entity) {
        super.delete(entity);
        //执行删除操作配置的sql增强
        this.doDelSql((CbsInspectionAppointmentEntity) entity);
    }

    public <T> Serializable save(T entity) {
        Serializable t = super.save(entity);
        //执行新增操作配置的sql增强
        this.doAddSql((CbsInspectionAppointmentEntity) entity);
        return t;
    }

    public <T> void saveOrUpdate(T entity) {
        super.saveOrUpdate(entity);
        //执行更新操作配置的sql增强
        this.doUpdateSql((CbsInspectionAppointmentEntity) entity);
    }

    /**
     * 默认按钮-sql增强-新增操作
     *
     * @return
     */
    public boolean doAddSql(CbsInspectionAppointmentEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-更新操作
     *
     * @return
     */
    public boolean doUpdateSql(CbsInspectionAppointmentEntity t) {
        return true;
    }

    /**
     * 默认按钮-sql增强-删除操作
     *
     * @return
     */
    public boolean doDelSql(CbsInspectionAppointmentEntity t) {
        return true;
    }

    /**
     * 替换sql中的变量
     *
     * @param sql
     * @return
     */
    public String replaceVal(String sql, CbsInspectionAppointmentEntity t) {
        sql = sql.replace("#{id}", String.valueOf(t.getId()));
        sql = sql.replace("#{contact_name}", String.valueOf(t.getContactName()));
        sql = sql.replace("#{phone}", String.valueOf(t.getPhone()));
        sql = sql.replace("#{mail}", String.valueOf(t.getMail()));
        sql = sql.replace("#{expect_date}", String.valueOf(t.getExpectDate()));
        sql = sql.replace("#{content}", String.valueOf(t.getContent()));
        sql = sql.replace("#{create_name}", String.valueOf(t.getCreateName()));
        sql = sql.replace("#{create_by}", String.valueOf(t.getCreateBy()));
        sql = sql.replace("#{create_date}", String.valueOf(t.getCreateDate()));
        sql = sql.replace("#{update_name}", String.valueOf(t.getUpdateName()));
        sql = sql.replace("#{update_by}", String.valueOf(t.getUpdateBy()));
        sql = sql.replace("#{update_date}", String.valueOf(t.getUpdateDate()));
        sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
        return sql;
    }

    public String genInAppId(CbsInspectionAppointmentEntity t) {
        if (StringUtil.isEmpty(t.getInAppId())) {
            List<CbsInspectionAppointmentEntity> inAppList = this.findHql("from CbsInspectionAppointmentEntity where date(createDate) = curdate()");
            String num = inAppList.size() + 1 + "";
            if (inAppList.size() < 10 && inAppList.size() > 0) {
                num = "0" + num;
            } else if (inAppList.size() == 0) {
                num = "01";
            }
            return "PM" + DataUtils.getDate("yyyyMMdd") + num;
        }
        return t.getInAppId();
    }

    public List<CbsInspectionAppointmentEntity> findAppointmentWithCinema(String cinemaId) {
        List<CbsInspectionAppointmentEntity> results = new ArrayList<CbsInspectionAppointmentEntity>();
        results = findHql("from CbsInspectionAppointmentEntity where cinema.id=? order by createDate desc", cinemaId);
        return results;
    }

    public List<CbsInspectionAppointmentEntity> findAppointmentWithCinemaAndSn(String cinemaId, String searchContent) {
        List<CbsInspectionAppointmentEntity> results = new ArrayList<CbsInspectionAppointmentEntity>();
        results = findHql("select distinct a from CbsInspectionAppointmentEntity  a join a.esList b where a.cinema.id=? and b.es.sn like '%" + searchContent + "%' order by a.createDate desc", cinemaId);
        return results;
    }

    @Override
    public String checkSnIfInAppoint(String snNums) {
        String re = "";
        if (StringUtil.isNotEmpty(snNums)) {
            String paramSn = "";
            String[] sns = snNums.split(",");
            for (String s : sns) {
                paramSn += "," + s;
            }
            paramSn = "'" + paramSn.substring(1).replace(",", "','") + "'";
            logger.info(paramSn);
            List<ZyEquipmentSpareEntity> approvalAppoints = findHql("select distinct b.es from CbsInspectionAppointmentEntity  a inner join a.esList b where a.status in ('1','4') and  b.es.id in (" + paramSn + ")");
            if (approvalAppoints.size() > 0) {

                for (ZyEquipmentSpareEntity es : approvalAppoints) {
                    re += "," + es.getSn();
                }
            }
        }
        return re.length() > 1 ? re.substring(1) : re;
    }

    @Override
    public boolean checkSection(int section) {
        Calendar c1 = Calendar.getInstance();
        int m = c1.get(Calendar.MONTH)+1;
        int currentSection = m/3 ;
        if(m%3 >= 0){
            currentSection++;
        }
        if(currentSection == 4){
            if(section != 1){
                return false;
            }
        }else{
            if(section - currentSection <= 1){
                return false;
            }
        }
        return true;
    }

    @Override
    public List<SectionEnum> generateExpectSectionSelect(int year) {
        List<SectionEnum> resultsSection = new ArrayList<SectionEnum>();
        Calendar c1 = Calendar.getInstance();
        int currentYear = c1.get(Calendar.YEAR);
        if(year <= 0){
            year = currentYear;
        }
        if(currentYear > year){
            return resultsSection;
        }else if (currentYear == year){
            resultsSection.addAll(SectionEnum.valueOfRestSection());
            if(resultsSection.size() > 2){
                return resultsSection.subList(1,resultsSection.size());
            }
        }else{
            resultsSection.add(SectionEnum.FIRST);
        }
        return resultsSection;
    }

    @Override
    public int[] generateExpectYearsSelect() {
        int[] years = new int[2];
        Calendar c1 = Calendar.getInstance();
        int year = c1.get(Calendar.YEAR);
        for(int i=0;i<2;i++){
            years[i] = year++;
        }
        if(SectionEnum.valueOfRestSection().size() <=1){
            return new int[]{years[1]};
        }
        return years;
    }

    @Override
    public Map genMapVo(CbsInspectionAppointmentEntity app) {
        Map m = new HashMap();
        m.put("id", app.getId());
        m.put("appNo", app.getInAppId());
        m.put("expectDate", app.getExpectDate() != null ? DateUtils.formatDate(app.getExpectDate(), "yyyy-MM-dd") : "");
        m.put("createDate", app.getCreateDate() != null ? DateUtils.formatDate(app.getCreateDate(), "yyyy-MM-dd") : "");
        m.put("contactName", app.getContactName());
        m.put("phone", app.getPhone());
        String statusText = "";
        /**状态 0.草稿 1.审批中 2.已完成 3.已取消 4.处理中*/
        switch (oConvertUtils.getString(app.getStatus())) {
            case "0":
                statusText = "待处理";
                break;
            case "1":
                statusText = "审批中";
                break;
            case "2":
                statusText = "已完成";
                break;
            case "3":
                statusText = "已取消";
                break;
            case "4":
                statusText = "处理中";
                break;
        }

        m.put("status", app.getStatus());
        m.put("statusText", statusText);
//        m.put("statusText", systemService.getTypeByCode("procurementNoteState",app.getStatus()));
        return m;
    }


}